package server

import (
	"context"
	configs2 "cron-go/configs"

	"cron-go/internal/app/router"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/gin-gonic/gin"
)

func init() {
	// 模式切换
	env := configs2.EnvConfig.ProjectEnv
	if env == "dev" {
		gin.SetMode(gin.DebugMode)
	} else if env == "test" {
		gin.SetMode(gin.TestMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}
}

func RunHTTP(HTTPPort string) {
	println("[LOG] Start HTTP Server on port", HTTPPort)
	host, err := os.Hostname()
	if err == nil {
		println("[LOG] Start name:", host)
	}
	router := router.SetupRouter()
	start(router, HTTPPort)
}

func start(router *gin.Engine, HTTPPort string) {
	// Listen and serve on 0.0.0.0:8080
	// router.Run(":80") 这样写就可以了，下面所有代码（go1.8+）是为了优雅处理重启等动作。可根据实际情况选择。
	var timeSecond time.Duration = 30
	srv := &http.Server{
		Addr:         HTTPPort,
		Handler:      router,
		ReadTimeout:  timeSecond * time.Second,
		WriteTimeout: timeSecond * time.Second,
	}
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			fmt.Printf("[ERROR]listen: %+v\n", err)
		}
	}()
	// 5秒后优雅Shutdown服务
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt) //syscall.SIGKILL
	<-quit
	println("Shutdown Server ...")
	var timeOut time.Duration = 5
	ctx, cancel := context.WithTimeout(context.Background(), timeOut*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		println("[INFO]Server Shutdown:%v", err)
	}
}
